
/*
 * Copyright 2002-2019 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/*
 *版权所有2002-2019原作者。
 *
 *根据Apache许可证2.0版（“许可证”）获得许可；
 *除非符合许可证，否则不得使用此文件。
 *您可以在以下地址获取许可证副本：
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 *除非适用法律要求或书面同意，软件
 *根据许可证分发的内容是按“原样”分发的，
 *无任何明示或暗示的保证或条件。
 *有关管理权限和
 *许可证下的限制。
 */

package org.springframework.beans.propertyeditors;

import java.beans.PropertyEditorSupport;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;

import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ReflectionUtils;

/**
 * Property editor for Collections, converting any source Collection
 * to a given target Collection type.
 *
 * <p>By default registered for Set, SortedSet and List,
 * to automatically convert any given Collection to one of those
 * target types if the type does not match the target property.
 *
 * @author Juergen Hoeller
 * @since 1.1.3
 * @see java.util.Collection
 * @see java.util.Set
 * @see java.util.SortedSet
 * @see java.util.List
 */
/**
 *集合的属性编辑器，转换任何源集合
 *指定的目标集合类型。
 *
 *＜p＞默认为Set、SortedSet和List注册，
 *自动将任何给定的集合转换为其中之一
 *如果类型与目标属性不匹配，则返回目标类型。
 *
 *@作者Juergen Hoeller
 *@自1.1.3起
 *@参见java.util.Collection
 *@参见java.util.Set
 *@参见java.util.SortedSet
 *@参见java.util.List
 */
public class CustomCollectionEditor extends PropertyEditorSupport {

	@SuppressWarnings("rawtypes")
	private final Class<? extends Collection> collectionType;

	private final boolean nullAsEmptyCollection;


	/**
	 * Create a new CustomCollectionEditor for the given target type,
	 * keeping an incoming {@code null} as-is.
	 * @param collectionType the target type, which needs to be a
	 * sub-interface of Collection or a concrete Collection class
	 * @see java.util.Collection
	 * @see java.util.ArrayList
	 * @see java.util.TreeSet
	 * @see java.util.LinkedHashSet
	 */
	/**
	 *为给定的目标类型创建新的CustomCollectionEditor，
	 *将传入的｛@code null｝保持原样。
	 *@param collectionType目标类型，它需要是
	 *Collection的子接口或具体的Collection类
	 *@参见java.util.Collection
	 *@参见java.util.ArrayList
	 *@参见java.util.TreeSet
	 *@参见java.util.LinkedHashSet
	 */
	@SuppressWarnings("rawtypes")
	public CustomCollectionEditor(Class<? extends Collection> collectionType) {
		this(collectionType, false);
	}

	/**
	 * Create a new CustomCollectionEditor for the given target type.
	 * <p>If the incoming value is of the given type, it will be used as-is.
	 * If it is a different Collection type or an array, it will be converted
	 * to a default implementation of the given Collection type.
	 * If the value is anything else, a target Collection with that single
	 * value will be created.
	 * <p>The default Collection implementations are: ArrayList for List,
	 * TreeSet for SortedSet, and LinkedHashSet for Set.
	 * @param collectionType the target type, which needs to be a
	 * sub-interface of Collection or a concrete Collection class
	 * @param nullAsEmptyCollection whether to convert an incoming {@code null}
	 * value to an empty Collection (of the appropriate type)
	 * @see java.util.Collection
	 * @see java.util.ArrayList
	 * @see java.util.TreeSet
	 * @see java.util.LinkedHashSet
	 */
	/**
	 *为给定的目标类型创建新的CustomCollectionEditor。
	 *＜p＞如果传入值是给定类型，则将按原样使用。
	 *如果它是不同的集合类型或数组，则将转换
	 *设置为给定集合类型的默认实现。
	 *如果该值为其他值，则使用
	 *将创建值。
	 *＜p＞默认的Collection实现是：ArrayList for List，
	 *SortedSet的TreeSet和Set的LinkedHashSet。
	 *@param collectionType目标类型，它需要是
	 *Collection的子接口或具体的Collection类
	 *@param nullAsEmptyCollection是否转换传入的｛@code null｝
	 *值设置为空集合（具有适当类型）
	 *@参见java.util.Collection
	 *@参见java.util.ArrayList
	 *@参见java.util.TreeSet
	 *@参见java.util.LinkedHashSet
	 */
	@SuppressWarnings("rawtypes")
	public CustomCollectionEditor(Class<? extends Collection> collectionType, boolean nullAsEmptyCollection) {
		Assert.notNull(collectionType, "Collection type is required");
		if (!Collection.class.isAssignableFrom(collectionType)) {
			throw new IllegalArgumentException(
					"Collection type [" + collectionType.getName() + "] does not implement [java.util.Collection]");
		}
		this.collectionType = collectionType;
		this.nullAsEmptyCollection = nullAsEmptyCollection;
	}


	/**
	 * Convert the given text value to a Collection with a single element.
	 */
	/**
	 *将给定的文本值转换为具有单个元素的集合。
	 */
	@Override
	public void setAsText(String text) throws IllegalArgumentException {
		setValue(text);
	}

	/**
	 * Convert the given value to a Collection of the target type.
	 */
	/**
	 *将给定值转换为目标类型的集合。
	 */
	@Override
	public void setValue(@Nullable Object value) {
		if (value == null && this.nullAsEmptyCollection) {
			super.setValue(createCollection(this.collectionType, 0));
		}
		else if (value == null || (this.collectionType.isInstance(value) && !alwaysCreateNewCollection())) {
			// Use the source value as-is, as it matches the target type.
			// 按原样使用源值，因为它与目标类型匹配。
			super.setValue(value);
		}
		else if (value instanceof Collection<?> source) {
			// Convert Collection elements.
			// 转换集合元素。
			Collection<Object> target = createCollection(this.collectionType, source.size());
			for (Object elem : source) {
				target.add(convertElement(elem));
			}
			super.setValue(target);
		}
		else if (value.getClass().isArray()) {
			// Convert array elements to Collection elements.
			// 将数组元素转换为集合元素。
			int length = Array.getLength(value);
			Collection<Object> target = createCollection(this.collectionType, length);
			for (int i = 0; i < length; i++) {
				target.add(convertElement(Array.get(value, i)));
			}
			super.setValue(target);
		}
		else {
			// A plain value: convert it to a Collection with a single element.
			// 纯值：将其转换为具有单个元素的集合。
			Collection<Object> target = createCollection(this.collectionType, 1);
			target.add(convertElement(value));
			super.setValue(target);
		}
	}

	/**
	 * Create a Collection of the given type, with the given
	 * initial capacity (if supported by the Collection type).
	 * @param collectionType a sub-interface of Collection
	 * @param initialCapacity the initial capacity
	 * @return the new Collection instance
	 */
	/**
	 *创建给定类型的集合
	 *初始容量（如果集合类型支持）。
	 *@param collectionType Collection的子接口
	 *@param initialCapacity初始容量
	 *@return新的Collection实例
	 */
	@SuppressWarnings({"rawtypes", "unchecked"})
	protected Collection<Object> createCollection(Class<? extends Collection> collectionType, int initialCapacity) {
		if (!collectionType.isInterface()) {
			try {
				return ReflectionUtils.accessibleConstructor(collectionType).newInstance();
			}
			catch (Throwable ex) {
				throw new IllegalArgumentException(
						"Could not instantiate collection class: " + collectionType.getName(), ex);
			}
		}
		else if (List.class == collectionType) {
			return new ArrayList<>(initialCapacity);
		}
		else if (SortedSet.class == collectionType) {
			return new TreeSet<>();
		}
		else {
			return new LinkedHashSet<>(initialCapacity);
		}
	}

	/**
	 * Return whether to always create a new Collection,
	 * even if the type of the passed-in Collection already matches.
	 * <p>Default is "false"; can be overridden to enforce creation of a
	 * new Collection, for example to convert elements in any case.
	 * @see #convertElement
	 */
	/**
	 *返回是否始终创建新集合，
	 *即使传入集合的类型已经匹配。
	 *<p>默认值为“false”；可以重写以强制创建
	 *例如，在任何情况下都可以转换元素。
	 *@参见#convertElement
	 */
	protected boolean alwaysCreateNewCollection() {
		return false;
	}

	/**
	 * Hook to convert each encountered Collection/array element.
	 * The default implementation simply returns the passed-in element as-is.
	 * <p>Can be overridden to perform conversion of certain elements,
	 * for example String to Integer if a String array comes in and
	 * should be converted to a Set of Integer objects.
	 * <p>Only called if actually creating a new Collection!
	 * This is by default not the case if the type of the passed-in Collection
	 * already matches. Override {@link #alwaysCreateNewCollection()} to
	 * enforce creating a new Collection in every case.
	 * @param element the source element
	 * @return the element to be used in the target Collection
	 * @see #alwaysCreateNewCollection()
	 */
	/**
	 *挂钩以转换每个遇到的集合/数组元素。
	 *默认实现只是按原样返回传入的元素。
	 *＜p＞可以被重写以执行某些元素的转换，
	 *例如，如果传入字符串数组，则将字符串转换为整数，并且
	 *应转换为一组整数对象。
	 *＜p＞仅在实际创建新集合时调用！
	 *如果传入集合的类型
	 *已匹配。将｛@link#alwaysCreateNewCollection（）｝重写为
	 *在任何情况下强制创建新集合。
	 *@param元素源元素
	 *@return要在目标集合中使用的元素
	 *@参见#alwaysCreateNewCollection（）
	 */
	protected Object convertElement(Object element) {
		return element;
	}


	/**
	 * This implementation returns {@code null} to indicate that
	 * there is no appropriate text representation.
	 */
	/**
	 *此实现返回｛@code null｝以指示
	 *没有适当的文本表示。
	 */
	@Override
	@Nullable
	public String getAsText() {
		return null;
	}

}
